// generateView.js
const chalk = require('chalk')
const path = require('path')
const fs = require('fs')
const resolve = (project, ...file) => path.resolve(project, ...file)
const log = message => console.log(chalk.green(`${message}`))
const successLog = message => console.log(chalk.blue(`${message}`))
const errorLog = error => console.log(chalk.red(`${error}`))
const defaultTemplate = require('./apptemplate')

const generateFile = (path, data) => {
    if (fs.existsSync(path)) {
        errorLog(`${path}文件已存在`)
        return
    }
    return new Promise((resolve, reject) => {
        fs.writeFile(path, data, 'utf8', err => {
            if (err) {
                errorLog(err.message)
                reject(err)
            } else {
                resolve(true)
            }
        })
    })
}
// 创建页面
const defaultPath = '/app/cloudfunctions-aliyun'

function createAppApi(targetPath, inputName, dbName, option) {
    return new Promise(async (resFn) => {
        let indexTemplate, addTemplate, delTemplate, updateTemplate, listTemplate, packageTemplate;
        const userProjectDirectory = process.cwd() + defaultPath
        indexTemplate = defaultTemplate.indexTemplate;
        addTemplate = defaultTemplate.addTemplate;
        delTemplate = defaultTemplate.delTemplate;
        updateTemplate = defaultTemplate.updateTemplate;
        listTemplate = defaultTemplate.listTemplate;
        packageTemplate = defaultTemplate.packageTemplate;
        const componentVueName = resolve(userProjectDirectory, `admin-${targetPath}-${inputName}-api`, 'index')
        const add = resolve(userProjectDirectory, `admin-${targetPath}-${inputName}-api`, 'modules', 'add')
        const del = resolve(userProjectDirectory, `admin-${targetPath}-${inputName}-api`, 'modules', 'del')
        const update = resolve(userProjectDirectory, `admin-${targetPath}-${inputName}-api`, 'modules', 'update')
        const list = resolve(userProjectDirectory, `admin-${targetPath}-${inputName}-api`, 'modules', 'list')
        const packages = resolve(userProjectDirectory, `admin-${targetPath}-${inputName}-api`, 'package')
        const componentDirectory = path.dirname(componentVueName)
        const addDirectory = path.dirname(add)
        const delDirectory = path.dirname(del)
        const updateDirectory = path.dirname(update)
        const listDirectory = path.dirname(list)
        const packageDirectory = path.dirname(packages)
        const hasComponentExists = fs.existsSync(componentVueName)
        if (hasComponentExists) {
            errorLog(`${inputName}页面已存在`)
            return
        } else {
            await dotExistDirectoryCreate(componentDirectory)
            await dotExistDirectoryCreate(addDirectory)
            await dotExistDirectoryCreate(delDirectory)
            await dotExistDirectoryCreate(updateDirectory)
            await dotExistDirectoryCreate(listDirectory)
            await dotExistDirectoryCreate(packageDirectory)
        }
        try {
            let columns = ''
            for (const field in option) {
                columns += `${field}: params.${field} ? new RegExp(\`^\${ params.${field} }\`, 'i'):dbCmd.exists(true),`
            }
            log(`生成云函数 crud admin - ${targetPath} - ${inputName} - api`)
            await generateFile(`${componentVueName}.js`, indexTemplate(dbName))
            await generateFile(`${add}.js`, addTemplate())
            await generateFile(`${del}.js`, delTemplate())
            await generateFile(`${update}.js`, updateTemplate())
            await generateFile(`${list}.js`, listTemplate(columns))
            await generateFile(`${packages}.json`, packageTemplate(`admin-${targetPath}-${inputName}-api`))
            successLog('生成云函数 crud 文件生成成功')
            resFn()
        } catch (e) {
            resFn()
            errorLog(e.message)
        }
    })
}

function dotExistDirectoryCreate(directory) {
    return new Promise((resolve) => {
        mkdirs(directory, () => {
            resolve(true)
        })
    })
}

// 递归创建目录
function mkdirs(directory, callback) {
    var exists = fs.existsSync(directory)
    if (exists) {
        callback()
    } else {
        mkdirs(path.dirname(directory), () => {
            fs.mkdirSync(directory)
            callback()
        })
    }
}
module.exports = {
    createAppApi
}